package com.excu.utils;

import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * 服务器端解密处理器，用于解密客户端发送的加密数据
 */
public class ServerDecryptHandler {
    private final String secretKey;
    
    /**
     * 构造方法
     * @param secretKey 解密密钥(必须与客户端加密密钥相同)
     */
    public ServerDecryptHandler(String secretKey) {
        // 验证密钥有效性
        if (secretKey == null || (secretKey.length() != 16 && secretKey.length() != 24 && secretKey.length() != 32)) {
            throw new IllegalArgumentException("密钥必须是16、24或32个字符长度");
        }
        this.secretKey = secretKey;
    }

    /**
     * 处理HTTP请求，解密获取原始数据
     * @param request HTTP请求对象
     * @return 解密后的原始JSON数据
     * @throws Exception 可能的异常
     */
    public String handleRequest(HttpServletRequest request) throws Exception {
        return handleRequest(request.getInputStream());
    }
    
    /**
     * 从输入流读取并解密数据
     * @param inputStream 请求输入流
     * @return 解密后的原始JSON数据
     * @throws Exception 可能的异常
     */
    public String handleRequest(InputStream inputStream) throws Exception {
        // 从输入流读取请求体
        StringBuilder requestBody = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                requestBody.append(line);
            }
        } catch (IOException e) {
            throw new Exception("读取请求数据失败", e);
        }
        
        // 解析JSON获取加密数据
        JSONObject jsonObject;
        try {
            jsonObject = JSONObject.parseObject(requestBody.toString());
        } catch (Exception e) {
            throw new Exception("解析请求数据失败，格式不是有效的JSON", e);
        }
        
        if (!jsonObject.containsKey("data")) {
            throw new Exception("请求数据格式错误，缺少data字段");
        }
        
        String encryptedData = jsonObject.getString("data");
        if (encryptedData == null || encryptedData.trim().isEmpty()) {
            throw new Exception("加密数据不能为空");
        }
        
        // 解密数据
        try {
            return EncryptionUtils.decrypt(encryptedData, secretKey);
        } catch (Exception e) {
            throw new Exception("数据解密失败: " + e.getMessage(), e);
        }
    }
}
    